
<!--
	作者：lsd
	时间：2020-4-27
	描述：已确认申请
-->
<template>
	<div class="m-view-doneList m-window">
		<!-- 搜索头 -->
		<div class="m-condition">
			<el-form
				:model="formSearch"
				ref="formSearch"
				label-width="90px"
				:inline-message="true"
				label-position="left"
			>
				<el-row :gutter="10">
					<el-col :span="5">
						<el-form-item label="工厂" class="rightItem">
							<el-select
								v-model="formSearch.plantCode"
								filterable
								clearable
								:filter-method="filterFactory"
								placeholder="请选择工厂"
							>
								<el-option
									v-for="item in optionsFactory"
									:key="item.plantCode"
									:label="item.plantName"
									:value="item.plantCode"
								>
									<span style="float: left">{{ item.plantName }}</span>
									<span style="float: right; color: #8492a6; font-size: 13px">{{ item.plantCode }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="批准日期" class="rightItem">
							<el-date-picker
								v-model="formSearch.auditDate"
								placeholder="开始日期"
								value-format="yyyy-MM-dd"
								clearable
								:picker-options="timeRange(formSearch.auditDateEnd, true)"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-date-picker
							v-model="formSearch.auditDateEnd"
							clearable
							placeholder="结束日期"
							value-format="yyyy-MM-dd"
							:picker-options="timeRange(formSearch.auditDate)"
						></el-date-picker>
					</el-col>
					<el-col :span="5">
						<el-form-item label="采购申请号" class="rightItem">
							<el-input v-model.trim="formSearch.requestNo" placeholder="请输入" clearable maxlength="20"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="物料描述" class="rightItem">
							<el-input v-model.trim="formSearch.matName" placeholder="请输入" clearable maxlength="20"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<el-col :span="5">
						<el-form-item label="任务号" class="rightItem">
							<el-input v-model.trim="formSearch.taskNo" placeholder="请输入" clearable maxlength="20"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="状态" class="rightItem">
							<el-select v-model="formSearch.state" clearable placeholder="请选择状态">
								<el-option
									v-for="item in stateOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="是否做单" class="rightItem">
							<el-select v-model="formSearch.hasPurchase" clearable placeholder="请选择是否做单">
								<el-option
									v-for="item in orderOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="2" :offset="3">
						<el-button type="primary" @click="search(true)">查询</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="recall">撤回</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="printBill('purchaseBill')">打印申请单</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>

		<!-- 表单 -->
		<div class="m-agTable m-bottom m-top2" v-loading="loading">
			<ag-grid-component
				ref="agGridComponent"
				:tableName="'doList'"
				:getGridOptions="gridOptions"
				:getColumnDefs="columnDefs"
				:getRowSelection="'multiple'"
				:isColFit="true"
				:systemInfo="$systemInfo"
			></ag-grid-component>
		</div>

		<!-- 页脚 -->
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pageInfo.currentPage"
				:page-sizes="[30,50,100,150,200 ]"
				:page-size="pageInfo.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
			></el-pagination>
		</div>

		<!-- 历史记录弹窗 -->
		<history-log :formData="historyData" :dialogVisible="diaShow" @dialogClose="diaShow = false"></history-log>
	</div>
</template>
  
<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import gridOptions from "lesso-common/public/gridOptions";
import Vue from "vue";
import historyLog from "./common/dialogSrmHistoryLog";

import { startPrint } from 'lesso-common/webprint'
import fileStream from "@/public/fileStream";
import apienv from '@/api/env';
import constant from "@/public/constant";
import print from "./common/printPc";


const ENV = apienv[constant.appenv]
/**
 * @group doneList
 * 已确认申请
 */
export default {
	name: 'doneList',
	components:{ historyLog },
	data () {
		return {
			formSearch: {//查询表
				plantCode: '',
				requestNo: '',
				//sapCreateDate: '',
				//sapCreateDateEnd: '',
				//purGroup: '',
				auditDate: new Date(new Date().getTime() - 30 * 24 * 3600 * 1000).Format('yyyy-MM-dd'),
				auditDateEnd: new Date().Format('yyyy-MM-dd'),
				//matCode: '',
				matName: '',
				//matgroup: '',
				taskNo: '',
				state: '',
				hasPurchase:''
			},
			optionsFactory: [], //工厂下拉框列表
			optionsTempFactory: [], //工具人，专门用来过滤的
			rowData: [], // 表格数据
			//表格参数
			gridOptions: '',
			columnDefs: [],
			//页脚参数
			pageInfo: {
				pageSize: 30,
				currentPage: 1,
			},
			total: 0,
			//加载参数
			loading: false,//页面的
			diaShow: false,
			historyData: {},//转派记录表
			// 状态选项
			stateOptions: [
				{ value: 1, label: '已确认' },
				{ value: 2, label: '已拒绝' },
				{ value: 3, label: '已转派' }
			],
			// 状态选项
			orderOptions: [
				{ value: 1, label: '已做' },
				{ value: 0, label: '未做' },
			
			]
		}
	},
	beforeMount () {
		this.gridOptions = {
			context: {
				componentParent: this
			},
			defaultColDef: {
        sortable: true
			},
			sideBar: {
        toolPanels:[
            {
                id: "columns",
                labelDefault: "Columns",
                labelKey: "columns",
                iconKey: "columns",
                toolPanel: "agColumnsToolPanel"
            }
				]
			},
			rowSelection: "multiple",
			rowDeselection: false,
			rowMultiSelectWithClick:true,
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true,
			enableFilter: true, //列过滤器
			enableSorting: true, //列排序
			animateRows: true, //排序动画
		}

		this.columnDefs = [
			{ checkboxSelection: true, headerCheckboxSelection: true, headerName: "任务号", field: "taskNo", width: 130 },
			
			{ headerName: "采购申请", field: "requestNo", width: 100 },
			{ headerName: "采购申请项目", field: "requestMxno", width: 115 },
			{ headerName: "物料编码", field: "matCode", width: 95 },
			{ headerName: "物料描述", field: "matName", width: 155 },
			{ headerName: "申请数量", field: "requestAmount", width: 90 },
			{ headerName: "单位", field: "unitCode", width: 65 },
			{ headerName: "申请部门", field: "purGroupName", width: 90 },
			{ headerName: "申请者", field: "requester", width: 78 },
			{ headerName: "备注", field: "memo", width: 105 },
			{ headerName: "负责人", field: "handlerName", width: 78 },
			{	headerName: "转派人", field: "transferName", width: 78, cellRenderer: (params) => {
					if (params.value) {
						return `<span style="position: absolute; right: 1px; bottom: 1px; left: 1px; top: 1px;background: #FFFF00;">
							${params.value}
						</span>`;
					} else {
						return '';
					}
				}
			},
			{	headerName: "状态", field: "state", width: 78,
				cellRenderer: (params) => {
					let tip = "";
					switch (params.value) {
						case 0:
							tip = "<span style='color: red'>未确认</span>";
							break;
						case 1:
							tip = "<span style='color: green'>已确认</span>";
							break;
						case 2:
							tip = "已拒绝";
							break;
						case 3:
							tip = "已转派";
							break;
						case 4:
							tip = "删除";
							break;
					}
					return tip
				}
			},
			{ headerName: "操作时间", field: "modifyDate", width: 150 },
			// { headerName: "采购订单", field: "requestId", width: 95 },
		
			{ headerName: "工厂", field: "plantName", width: 150 },
			{ headerName: "采购订单号", field: "purOrdNo", width: 105 },
			{ headerName: "采购订单项目", field: "purOrdMxNo", width: 115 },
			{ headerName: "申请日期", field: "sapCreateDate", width: 90, hide: true },
			{ headerName: "交货日期", field: "deliveryDate", width: 150, hide: true },
			{ 
                headerName: "转派记录",
                 width: 120, 
				cellRendererFramework: Vue.extend({
                    template: `<span>
                                    <el-button 
                                        type="text" 
                                        class="rendererClass" 
                                        size="mini" 
                                        @click="openHistoryDia(params.data)">
                        查看
                        </el-button>
                    </span>`,
                    methods: {
                        /**
                         * @vuese
                         * 项目列表的按钮点击事件
                         * 
                         * @arg row:行数据;
                         */
                        openHistoryDia( row) {
                                        this.params.context.componentParent.historyData = row;
                                        this.params.context.componentParent.diaShow = true;
                                    },
                                }
                        })
			}	
		];

	},
	mounted () {
		this.search();
		this.getFactoryList();
	},
	methods: {
		/**
		 * @vuese
		 * 查询方法
		 * 
		 * @arg isClick是布尔值， true就是点击触发，false就是非点击触发
		 */
		search (isClick) {
			this.loading = true;
			this.pageInfo.currentPage = isClick ? 1 : this.pageInfo.currentPage;
			let param = {
				...this.formSearch,
				handler: this.$global.user.idmNum,
				...this.pageInfo,
			};

			//参数兜底
			//if( param.sapCreateDate && !param.sapCreateDateEnd ){
			//	param.sapCreateDateEnd = this.getNowTime();
			//}
			//if( !param.sapCreateDate && param.sapCreateDateEnd ){
			//	param.sapCreateDate = '1970-01-01';
			//}
			if (!param.auditDate && param.auditDateEnd) {
				param.auditDate = '1970-01-01';
			}
			if (param.auditDate && !param.auditDateEnd) {
				param.auditDateEnd = this.getNowTime();;
			}

			_Api
				.getDoneList(param)
				.then(res => {
					this.loading = false;
					if (res.data.code == 1) {
						let list = res.data.rows;
						//时间填写
						this.rowData = list.map(e => {
							if (e.modifyDate == null || e.modifyDate == '') {
								e.modifyDate = e.createDate
							}
							return e
						})
						this.total = res.data.total
						this.$refs.agGridComponent.gridOptions.api.setRowData(this.rowData);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loading = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese
		 * 撤回方法
		 */
		recall () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			if (row.length <= 0) {
				this.$alert("提示：请至少选择一个任务", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			}
			let list = [];
			for (let i = 0; i < row.length; i++) {
				let { id, sapFlag, taskNo, taskMxno, requestId, requestNo, requestMxno, handler, handlerName, chandler, chandlerName, memo, state } = row[i];
				let param = {
					id,
					taskNo,
					taskMxno,
					requestId,
					requestNo,
					requestMxno,
					handler,
					handlerName,
					chandler,
					chandlerName,
					memo,
					state,
					sapFlag,
					modifyerId: this.$global.user.id,
					modifyer: this.$global.user.employeeName//修改人
				}
				list.push(param)
			}

			this.$confirm(`是否撤回该任务`, {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				this.loading = true;
				_Api
					.recallDoneList(list)
					.then(res => {
						this.loading = false;
						if (res.data.code == 1) {
							this.$message({
								message: `撤回成功！`,
								type: "success"
							});
							this.search();//刷新
						} else {
							this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						}
					})
					.catch(err => {
						this.loading = false;
						this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					});
			})
		},

		/**
     * @vuese
     * 根据账号获取工厂列表方法
     */
		getFactoryList () {
			this.loadingDia = true;
			_Api
				.getFactoryListBySapNum()
				.then(res => {
					this.loadingDia = false;
					if (res.data.code == 1) {
						this.optionsFactory = res.data.rows;
						this.optionsTempFactory = res.data.rows;
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loadingDia = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese
		 * 改变页脚总条数方法
		 */
		handleSizeChange (val) {
			this.pageInfo.pageSize = val;
			this.pageInfo.currentPage = 1;
			this.search();
		},

		/**
		 * @vuese
		 * 翻页方法
		 */
		handleCurrentChange (val) {
			this.pageInfo.currentPage = val;
			this.search();
		},

		/**
     * @vuese
     * 过滤工厂
     * 
     * @arg value:传入的是检索值, 用于过滤
     */
		filterFactory (value) {
			if (value != '') {
				this.optionsFactory = this.optionsTempFactory.filter(item => item.plantCode.indexOf(value) > -1 || item.plantName.indexOf(value) > -1)
			} else {
				this.optionsFactory = this.optionsTempFactory
			}
		},

		/**
     * @vuese
     * 获取当天的时间 格式：yyyy-mm-dd
     */
		getNowTime () {
			let myDate = new Date();
			let month = myDate.getMonth() + 1;
			let day = myDate.getDate();
			let nowTime = `${myDate.getFullYear()}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
			return nowTime;
		},

		/**
     * @vuese
     * 日期可选范围
		 * 
		 * @arg startTime参数是时间， 代表为最小时间； flag是布尔值， true为开始时间范围， false为结束时间范围
     */
		timeRange (startTime, flag) {
			return {
				disabledDate (time) {
					let tempTime = new Date(startTime).getTime() || 0;
					let minTime = time.getTime() + 24 * 60 * 60 * 1000;

					if (tempTime == 0) {
						return time.getTime() > Date.now();
					}
					else if (flag) {
						return time.getTime() > tempTime;
					}
					else {
						return minTime < tempTime || time.getTime() > Date.now();
					}
				}
			}
		},
        /**
         * @vuese
         * 打印采购申请单
         * @arg 参数tempType为打印模板编码
         */
		printBill (tempType) {
            const { state } = this.formSearch
            if (constant.userAgent == 'web'){
                fileStream.getFileInfo(tempType).then((data) => {
                    startPrint({
                        basicUrl: ENV['srm'], //权限接口地址
                        reportUrl: `${ENV['srm']}download2?viewPath=${data.url}&groupName=${data.groupName}`, //打印模板地址
                        dataUrl: 'mstMyTodoTask/printUnconfirmedRequest', //数据接口地址
                        params: {
                            ...this.formSearch,
                            'token': '',
                            'handler': this.$global.user.idmNum,
                            'state': state || 4
                        }, //参数对象
                        printType: 'preview'     // 打印方式print直接打印，preview先预览
                    })
                }).catch((err) => {
                    this.$alert(err, {
                        showClose: false,
                        confirmButton: "确定",
                        customClass: "alertFailure"
                    });
                })
            } else {
                let params = {
                    ...this.formSearch,
                    'handler': this.$global.user.idmNum,
                    'state': state || 4
                }
                print.printPc("purchaseBill_pc",params)
            }
		}
	}
}
</script>
  
<style lang="less">
.m-view-doneList {
	.el-form {
		.el-form-item {
			margin-bottom: 0px;
		}
	}
}
</style>